<template>
  <md-page title="队员管理" isBtn :btnTextItems="data.btnTextItems" @btnClick="handleInvite">
    <view class="container">
      <view class="card" v-for="item in data.list" :key="item.id">
        <uni-section
          class="section"
          :title="item.truename"
          :sub-title="item.mobile"
          type="line"
          @click="() => handleTell(item.mobile)">
          <view class="content flex-l">
            <uni-tag :text="item.sex == 1 ? '男' : '女'" :custom-style="data.customStyle" />
            <uni-tag :text="item.age + '岁'" :custom-style="data.customStyle" />
            <uni-tag v-show="item?.size" :text="item.size" :custom-style="data.customStyle" />
          </view>
          <view class="bottom-action flex-l" v-show="item.is_main == 1">
            <view>
              <uni-tag :inverted="true" text="申请退赛" type="error" size="mini" v-show="item.is_apply_quit == 1" />
            </view>
            <view class="flex-l">
              <view
                @click.stop="() => handleChangeLeader(item.id)"
                v-if="
                  [TeamUserButtonState.组队中, TeamUserButtonState.组队成功].indexOf(
                    data.teamInfo?.user_button_state || 0
                  ) !== -1
                ">
                <uni-tag circl text="移交队长" type="warning" size="mini" />
              </view>
              <view
                @click.stop="() => handleDel(item.id)"
                v-if="data.teamInfo?.user_button_state == TeamUserButtonState.组队中">
                <uni-tag circl text="移除队员" type="error" size="mini" class="m-left-20" />
              </view>
            </view>
          </view>
        </uni-section>
      </view>
    </view>
  </md-page>
</template>

<script setup lang="ts">
import { reactive } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
// 接口
import {
  signTeamMemberChangeHeader,
  signTeamMemberList,
  signTeamMemberRemove,
  signTeamSubmit,
  signTeamDetail,
  signTeamRemove,
  signTeamCancelSubmit,
} from '@/api';
import type { SignTeam } from '@/api/data';
// 工具
import { TeamUserButtonState } from '@/api/enum';

const data = reactive<any>({
  btnTextItems: [],
  teamInfo: {},
  active_id: -1,
  sign_team_id: -1,
  invite_code: '',
  customStyle: `background-color: #F7F7F7; border-color: #F7F7F7; color: #333333; margin-right: 10rpx;`,
  list: [],
  configInfo: {},
});

const handleInvite = (info: any) => {
  const { key } = info.item;
  if (key === 'submit') {
    uni.showModal({
      title: '提示',
      content: '是否提交队伍?',
      success: res => {
        if (res.confirm) {
          fetchSignTeamSubmit();
        }
      },
    });
    return;
  }

  // 取消提交
  if (key === 'cancel_submit') {
    uni.showModal({
      title: '提示',
      content: '取消后可以继续添加成员！',
      success: res => {
        if (res.confirm) {
          fetchSignTeamCancelSubmit();
        }
      },
    });
    return;
  }

  // 解散队伍
  if (key === 'disband') {
    uni.showModal({
      title: '提示',
      content: '是否确定解散队伍？',
      success: res => {
        if (res.confirm) {
          fetchSignTeamRemove();
        }
      },
    });
  }
};

// 队伍解散
const fetchSignTeamRemove = async () => {
  try {
    const res = await signTeamRemove({ sign_team_id: data.sign_team_id });
    uni.showModal({
      title: '提示',
      content: res?.msg || '解散成功',
      showCancel: false,
      success: res => {
        if (res.confirm) {
          uni.redirectTo({
            url: '/pages/activity/detail?active_id=' + data.active_id,
          });
        }
      },
    });
  } catch (e) {
    //TODO handle the exception
  }
};

// 移交队长
const handleChangeLeader = (id: number) => {
  uni.showModal({
    title: '提示',
    content: '是否移交该队长',
    success: res => {
      if (res.confirm) {
        fetchSignTeamMemberChangeHeader(id);
      }
    },
  });
};

// 移除队员
const handleDel = (id: number) => {
  uni.showModal({
    title: '提示',
    content: '移除队员时，将会把他(她)携带的成员一起移除！请确认是否进行移除操作？',
    success: res => {
      if (res.confirm) {
        fetchSignTeamMemberRemove(id);
      }
    },
  });
};

// 拨打电话
const handleTell = (phone: string) => {
  if (!phone) return;
  uni.makePhoneCall({
    phoneNumber: phone,
  });
};

/**
 * 接口相关
 */
// 队员列表
const fetchSignTeamMemberList = async (params: SignTeam.MemberList.Body) => {
  try {
    const res = await signTeamMemberList(params);
    data.list = res.data;
  } catch (error) {}
};

// 移除队员
const fetchSignTeamMemberRemove = async (id: number) => {
  try {
    const res = await signTeamMemberRemove({ sign_id: id });
    uni.showModal({
      title: '提示',
      content: res?.msg || '移除队员成功',
      showCancel: false,
      success: res => {
        if (res.confirm) {
          fetchSignTeamMemberList({
            active_id: data.active_id,
            sign_team_id: data.sign_team_id,
          });
        }
      },
    });
  } catch (error) {}
};

// 移交队长
const fetchSignTeamMemberChangeHeader = async (id: number) => {
  uni.showLoading({
    title: '处理中...',
    mask: true,
  });
  try {
    const res = await signTeamMemberChangeHeader({ sign_id: id });
    uni.showModal({
      title: '提示',
      content: res?.msg || '移交队长成功',
      showCancel: false,
      success: res => {
        if (res.confirm) {
          uni.redirectTo({
            url: '/pages/activity/detail?active_id=' + data.active_id,
          });
        }
      },
    });
  } catch (error) {}
  uni.hideLoading();
};

// 提交队伍
const fetchSignTeamSubmit = async () => {
  try {
    const res = await signTeamSubmit({
      sign_team_id: data.sign_team_id,
    });
    uni.showModal({
      title: '提示',
      content: res?.msg || '提交队伍成功',
      showCancel: false,
      success: res => {
        if (res.confirm) {
          uni.redirectTo({
            url: '/pages/activity/detail?active_id=' + data.active_id,
          });
        }
      },
    });
  } catch (error) {}
};

// 取消提交队伍
const fetchSignTeamCancelSubmit = async () => {
  try {
    const res = await signTeamCancelSubmit({
      sign_team_id: data.sign_team_id,
    });
    uni.showModal({
      title: '提示',
      content: res?.msg || '取消提交队伍成功',
      showCancel: false,
      success: res => {
        if (res.confirm) {
          uni.redirectTo({
            url: '/pages/activity/detail?active_id=' + data.active_id,
          });
        }
      },
    });
  } catch (error) {}
};

onLoad(async (option: any) => {
  data.active_id = option?.active_id;
  data.sign_team_id = option?.sign_team_id;
  const _teamInfo = option?.teamInfo ? JSON.parse(option.teamInfo) : '';
  if (_teamInfo) {
    data.teamInfo = _teamInfo;
    data.invite_code = _teamInfo.invite_code;
  }
  fetchSignTeamMemberList({ ...option });

  // 是否要引流润无声的相关处理
  const configInfo = uni.getStorageSync('configInfo');
  if (Object.keys(configInfo || {})?.length > 0) {
    const parseInfo = JSON.parse(configInfo);
    data.configInfo = parseInfo;
  }
  // 后台控制按钮样式
  let commonStyle = (num: number = 1) => ({
    color: data.configInfo[`button_color${num}`] || '#1CA4C0',
    textColor: data.configInfo[`button_color${num}_text`] || '#ffffff',
  });

  const res = await signTeamDetail({ sign_team_id: data.sign_team_id });
  const _is_true = res.data?.is_true == 1;
  const user_button_state = res.data?.user_button_state;
  data.btnTextItems = [
    {
      text: '解散队伍',
      key: 'disband',
      hide: _is_true || ![TeamUserButtonState.组队中, TeamUserButtonState.组队成功].includes(user_button_state),
      ...commonStyle(),
    },
    {
      text: '提交队伍',
      key: 'submit',
      hide: user_button_state != TeamUserButtonState.组队中,
      ...commonStyle(),
    },
    {
      text: '取消提交',
      key: 'cancel_submit',
      hide: _is_true || user_button_state != TeamUserButtonState.组队成功,
      ...commonStyle(2),
    },
  ];
});
</script>

<style lang="scss" scoped>
.container {
  padding: 30rpx;
  & > view {
    margin-bottom: 20rpx;
  }
  .add-btn {
    font-size: $fs-28;
    line-height: 88rpx;
  }
  .card {
    width: 690rpx;
    min-height: 220rpx;
    background: #ffffff;
    border-radius: 20rpx;
    position: relative;
    .section {
      border-radius: 20rpx;
      .icon {
        position: absolute;
        top: 0;
        right: 0;
      }
    }
    .content {
      padding: 0 20px;
    }
    .tag {
      padding: 0 4rpx;
      height: 40rpx;
      line-height: 40rpx;
      background: #f7f7f7;
      border-radius: 20rpx;
    }
  }
  .bottom-action {
    margin-top: 12px;
    justify-content: space-between;
    padding: 0 20px 20rpx 20px;
  }
}

// 弹窗相关
.popup-content {
  @mixin flex-l-c {
    display: flex;
    flex-direction: column;
    align-items: center;
  }
  @include flex-l-c;
  padding: 15px;
  min-height: 500rpx;
  width: calc(680rpx - 30px);
  .image {
    flex: 1;
  }
  .bottom-btn {
    width: 100%;
    height: 88rpx;
    line-height: 88rpx;
    margin-top: 30rpx;
    background: black;
    color: white;
    font-size: 34rpx;
    text-align: center;
  }
}
</style>
